<?php

namespace app\controller;

use app\model\Sites;
use support\Request;

/**
 * 站点配置的增删改查
 */
class SitesController
{
  // 设定无需鉴权的函数
  protected $noNeedLogin = [];

  public function index(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id']);
      try {
        if (isset($data['id']) && $data['id'] != '') {
          $result = Sites::where('id', $data['id'])->find($data);
        } else {
          $result = Sites::select();
        }
        return json(["code" => 200, "msg" => "获取成功", "data" => $result]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 添加站点配置
   */
  public function add(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['site_name', 'site_url', 'api_url', 'passkey', 'download_limit', 'upload_limit', 'status', 'request_interval']);
      try {
        Sites::create($data);
        return json(["code" => 200, "msg" => "站点添加成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 更新站点信息
   */
  public function update(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id', 'site_name', 'site_url', 'api_url', 'passkey', 'download_limit', 'upload_limit', 'status', 'request_interval']);
      try {
        $site = new Sites;
        $list = [
          $data,
        ];
        $site->saveAll($list);
        return json(["code" => 200, "msg" => "站点修改成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 站点删除
   */
  public function delete(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id']);
      try {
        Sites::where('id', $data['id'])->delete();
        return json(["code" => 200, "msg" => "站点删除成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 检索出已经配置passkey的站点
   */
  public function sitepasskey(Request $request)
  {
    if ($request->method() == "POST") {
      try {
        $data = Sites::where('passkey', '!=', null)->select();
        return json(["code" => 200, "data" => $data]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }

    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }
}
